package com.baliejun.springsell.controller;


import com.baliejun.springsell.bean.ProductCategory;
import com.baliejun.springsell.bean.ProductInfo;
import com.baliejun.springsell.service.ProductCategoryService;
import com.baliejun.springsell.service.ProductInfoService;
import com.baliejun.springsell.util.ResultVOUtil;
import com.baliejun.springsell.viewbean.ProductCategoryVO;
import com.baliejun.springsell.viewbean.ProductInfoVO;
import com.baliejun.springsell.viewbean.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: LiejunBa
 * @Description:买家商品
 * @Date: 2020/12/2 10:50 上午
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProductInfoService productInfoService;


    @GetMapping("/list")
    public ResultVO list(){

        //注意：不要讲数据库的查询放到for循环中

        //1.查询所有的上架商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        //获取所有上架商品的category
        List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        //2.查询类目（一次查询）
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeList);
        //3.数据拼装
        List<ProductCategoryVO> productCategoryVOList = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList){
            ProductCategoryVO productCategoryVO = new ProductCategoryVO();
            productCategoryVO.setCategoryType(productCategory.getCategoryType());
            productCategoryVO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList){
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO(productInfo.getProductId(),productInfo.getProductName(),productInfo.getProductPrice(), productInfo.getProductDescription(), productInfo.getProductIcon());
                    productInfoVOList.add(productInfoVO);
                }
            }
            productCategoryVO.setProductInfoVOList(productInfoVOList);
            productCategoryVOList.add(productCategoryVO);

        }

        return ResultVOUtil.success(productCategoryVOList);
    }

}
